package com.tomkk;

import com.google.gson.Gson;
import com.tomkk.entity.AchievementListItem;
import com.tomkk.utils.Error;
import com.tomkk.utils.MysqlOperation;
import com.tomkk.utils.Success;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * Created by Tomkk on 2016/5/31.
 */
@WebServlet(name = "GetAllMyAchievementServlet",urlPatterns = "/getAllMyAchievement")
public class GetAllMyAchievementServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        int user_id = Integer.parseInt(request.getParameter("user_id"));
        String sql = "SELECT achievement_title,achievement_id,nickname,achievement_publish_time,headimage FROM achievement,user WHERE achievement.user_id ="+user_id+" AND  achievement_isuse = true AND achievement.user_id = user.user_id;";
        MysqlOperation operation = new MysqlOperation();
        operation.checkConn();
        ResultSet resultSet = operation.query(sql);
        Gson gson = new Gson();
        String json = null;
        ArrayList<AchievementListItem> achievementListItems = new ArrayList<>();
        if(resultSet == null){
            json = gson.toJson(new Error(2,"服务器错误"));
        }else{
            try {
                while(resultSet.next()) {
                    String achievement_title = resultSet.getString("achievement_title");
                    int achievement_id = resultSet.getInt("achievement_id");
                    String nickname = resultSet.getString("nickname");
                    String achievement_publish_time = resultSet.getString("achievement_publish_time");
                    String headimage = resultSet.getString("headimage");
                    AchievementListItem item = new AchievementListItem(achievement_id,achievement_title,nickname,achievement_publish_time,headimage);
                    achievementListItems.add(item);
                }
                json = gson.toJson(new Success(0,achievementListItems));
            } catch (SQLException e) {
                e.printStackTrace();
                json = gson.toJson(new Error(2,"服务器错误"));
            }
        }
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.flush();
        try {
            operation.closeDB();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
